Ext.ns('designer.properties');

Ext.define('designer.properties.Panel',{
	extend:'Ext.Panel',
	layout:'fit',
	border:false,
	
	searchPanel:null,
	dataStore:null,
	dataGrid:null,
	controllerUrl:'',
	autoScroll:false,
	
	objectName:null,
	
	initComponent:function()
	{
		this.searchPanel = Ext.create('SearchPanel',{			
			fieldNames:['name'],
			local:true,
			width:130,
			hideLabel:true
		});		
		
		this.dataGrid = Ext.create('Ext.grid.property.Grid', {      
			border:false,
			autoScroll:true,
			tbar:[this.searchPanel],
			listeners:{
				propertychange:{
					fn:this.onChange,
					scope:this
				}
			},
			source:{}
		});
		
		this.searchPanel.store = this.dataGrid.getStore();

		this.items = [this.dataGrid];
		this.callParent(arguments);
		this.loadProperties();

		this.addEvents(
	            /**
	             * @event dataSaved
	             */
	           'dataSaved'
	    );  
	},
	loadProperties:function(){
		Ext.Ajax.request({
		 	url:this.controllerUrl + 'list',
		 	method: 'post',
		 	scope:this,
		 	params:{
		 		object:this.objectName
		 	},
		    success: function(response, request) {
		 		response =  Ext.JSON.decode(response.responseText);
		 		if(response.success){
		 			this.dataGrid.setSource(response.data);
		 		}else{
		 			this.dataGrid.setSource({});
		 		}
		    },
		    failure:function() {
		       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		    }
		 });
	},
	onChange:function( source, recordId, value, oldValue, eOpts){
		if(value == oldValue)
			return;
		
		Ext.Ajax.request({
		 	url:this.controllerUrl + 'setproperty',
		 	method: 'post',
		 	scope:this,
		 	params:{
		 		object:this.objectName,
		 		name:recordId,
		 		value:value
		 	},
		    success: function(response, request) {
		 		response =  Ext.JSON.decode(response.responseText);
		 		if(!response.success){
		 			this.dataGrid.suspendEvents();
		 			this.dataGrid.setProperty(recordId , oldValue);
		 			this.dataGrid.resumeEvents();
		 			Ext.Msg.alert(appLang.MESSAGE,desLang.cantSaveProperty + ' "'+recordId+'"');
		 		}
		 		this.fireEvent('dataSaved');
		    },
		    failure:function() {
		       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		    }
		 });
	}
});